package com.lizi.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;



/**
 * 读取文件内容，并放到缓存中
 * 
 * @author Mark Hsiu
 *
 */
public class FilesTools {

	private static Logger logger = Logger.getLogger(FilesTools.class);

	private static Map<String, Properties> config = new HashMap<String, Properties>();
	
	private static ClasspathFileReader configReader = null;

	/**
	 * 获取*.properties文件
	 * @param entry 文件名称
	 * @return
	 */
	public static Properties getProperties(String entry) {
		entry = entry.toLowerCase().indexOf(".properties")>0 ? 
					entry :
						entry.toLowerCase()+".properties"; 
		
		if(isNotExistPropertiesFile(entry)){
			initConfigReader();
			InputStream is=null;
			try {
				File file = configReader.getFile(entry);
				is = new FileInputStream(file);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			
			if (is == null) {
				logger.error("[ERROR] Could not locate the filter config file: "+ entry);
			} else {
				try {
					Properties property= new Properties();
					property.load(is);
					config.put(entry,property);
					logger.info("config size:" + config.toString().getBytes().length
							+ " /Bytes ");
					logger.info("config files size :" + config.size());
				} catch (IOException e) {
					logger.error("[ERROR] There was a problem reading the filter config file: "+ entry, e);
				} finally {
					try {
						is.close();
					} catch (IOException ioe) {
						logger.error("[ERROR] Unable to close config file", ioe);
					}
				}
			}
		}
		
		return config.get(entry);
	}

	public static String getJsonEntry(String jsonFile) {
		
			initConfigReader();
			try {
				File file = configReader.getFile(jsonFile);
				return configReader.getFileContent(file);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		

		return null;
	}

	 
	
	private static boolean isNotExistPropertiesFile(String fileName) {
		return config.get(fileName) == null ? true : false;
	}
	

	private static void initConfigReader() {
		if (configReader == null) {
			configReader = new ClasspathFileReader();
		}
	}
	/**
	 * 修改或添加键值对 如果key存在，修改, 反之，添加。
	 * @param filePath 文件路径，即文件所在包的路径，例如：config/spring.properties
	 * @param key 键
	 * @param value 键对应的值
	 */
	public static void writeData(String filePath, String key, String value)throws Exception  {
//	
			Properties prop = new Properties();// 属性集合对象 
			FileInputStream fis = new FileInputStream(filePath);// 属性文件输入流 
			prop.load(fis);// 将属性文件流装载到Properties对象中 
			fis.close();// 关闭流 
			// 获取属性值，sitename已在文件中定义 
			logger.debug("获取属性值："+key+"=" + prop.getProperty(key)); 
			// 获取属性值，country未在文件中定义，将在此程序中返回一个默认值，但并不修改属性文件 
			// 修改sitename的属性值 
			prop.setProperty(key, value); 
			// 文件输出流 
			FileOutputStream fos = new FileOutputStream(filePath); 
			// 将Properties集合保存到流中 
			prop.store(fos, "Copyright (c) Boxcode Studio"); 
			fos.close();// 关闭流 
			
			logger.debug("获取修改后的属性值："+key+"=" + prop.getProperty(key)); 
			logger.debug("文件路径："+filePath);
	}
	
	
}
